// 导入Vue中的ref、computed、reactive和pinia中的defineStore
import { ref, computed, reactive } from 'vue'
import { defineStore } from 'pinia'
import { showToast } from 'vant';
import { showConfirmDialog } from 'vant';
// 定义一个接口ICart，用于描述购物车中的商品
interface ICart {
    restorativesid: number,
    restorativesname: string,
    restorativesprice: number,
    restorativescount: number,
    restorativesinven: string,
    restorativesstate: string,
    restorativestitle: string,
    restorativesimage: string,
    restorativesdesc: string,
    restorativestype: string,
}
// 定义一个名为useShoppingcart的store
export const useShoppingcart = defineStore('shoppingcart', () => {
    // 从localStorage中获取购物车数据
    const localStorageCart = localStorage.getItem('yjz-cart');
    // 将购物车数据转换为reactive对象
    let cart = reactive<ICart[]>(localStorageCart ? JSON.parse(localStorageCart) : []);
    // 加入购物车
    const addcart = (item: any) => {
        // 判断购物车中是否已经存在该商品
        let flag = cart.some(items => items.restorativesid === item.restorativesid);
        if (flag) {
            // 如果存在，则将该商品的数量加1
            cart.map((data: any) => {
                if (data.restorativesid === item.restorativesid) {
                    data.restorativescount += 1;
                }
                return data;
            })
        } else {
            if (cart.length < 5) {
                // 如果不存在，则将该商品加入购物车
                cart.push(item);
            } else {
                showToast('最多支持添加5种药品');
            }
        }
        localStorage.setItem('yjz-cart', JSON.stringify(cart));
    }
    // 减少购物车
    const reducecart = (item: any) => {
        const index = cart.findIndex(data => data.restorativesid === item.restorativesid);
        if (index !== -1) {
            if (cart[index].restorativescount > 1) {
                cart[index].restorativescount -= 1;
                localStorage.setItem('yjz-cart', JSON.stringify(cart));
            } else {
                showConfirmDialog({
                    title: '删除',
                    message: '确认删除商品吗?',
                })
                    .then(() => {
                        cart.splice(index, 1);
                        localStorage.setItem('yjz-cart', JSON.stringify(cart));
                        location.reload();
                    })
                    .catch(() => {
                        showToast('已取消删除');
                    });
            }

        }
    }
    return { cart, addcart, reducecart }
})
